package com.robot.mannge.common.exception;

import cn.hutool.extra.servlet.ServletUtil;
import com.robot.mannge.common.result.BaseResult;
import com.robot.mannge.common.result.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 统一的异常处理
 *
 * @author mileswan
 */
@ControllerAdvice
@Slf4j
public class KabobExceptionHandler {

    //    final String errorMsgTpl = "捕获到%s异常,ip:%s,url:%s,params:%s,header:%s,body:%s";
    final String errorMsgTpl = "捕获到%s异常,ip:%s,url:%s,params:%s,body:%s";

    /**
     * @Author: mwan
     * @Description: 系统异常捕获处理
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public BaseResult<?> javaExceptionHandler(HttpServletRequest request, Exception ex) {//APIResponse是项目中对外统一的出口封装，可以根据自身项目的需求做相应更改
        //异常写入普通日志
        log.error(getErrorMsg(request, Exception.class.getSimpleName()), ex);

        return BaseResult.failed(ResultCode.ERROR, (ex.getMessage() == null || ex.getMessage().replace(" ", "").equals("")) ? "服务器发生异常" :
                ex.getMessage());
    }

    String getErrorMsg(HttpServletRequest request, String exceptionName) {
//        Map<String, String> headerMap = ServletUtil.getHeaderMap(request);
        Map<String, String> paramMap = ServletUtil.getParamMap(request);
        String body = ServletUtil.getBody(request);
        String ip = ServletUtil.getClientIP(request);
        String requestUrl = request.getRequestURI();

        return String.format(errorMsgTpl, exceptionName, ip, requestUrl, paramMap, body);
    }

    /**
     * @Author: mwan
     * @Description: 自定义异常捕获处理
     */
    @ResponseBody
    @ExceptionHandler(value = KabobException.class)//KabobException是自定义的一个异常
    public BaseResult<?> kabobExceptionHandler(HttpServletRequest request, KabobException ex) {
        //异常写入普通日志
        log.error(getErrorMsg(request, KabobException.class.getSimpleName()), ex, ex);

        return ex.getApiResponse();
    }

    /**
     * @Author: mwan
     * @Description: 自定义警报捕获处理
     */
    @ResponseBody
    @ExceptionHandler(value = KabobWarning.class)//KabobWarning是自定义的一个警报
    public BaseResult<?> sstarWarningHandler(KabobWarning ex) {

        return ex.getApiResponse();
    }

}

